import { useRef, useState } from 'react';
import { useDebounce, useHandler } from '@cfe/hooks';
import { Checkbox, Divider, Select, Space, Spin } from 'antd';
import { camelizeKeys } from 'humps';

import { fetchLabelText } from '@/services/label';
import useLaunch from '@/useLaunch';

import BatchUpload from './BatchUpload';
import ViewAll from './ViewAll';

const AdvancedAutoComplete = ({ value, onChange, id, ...props }) => {
  const [textValues, setTextValues] = useState([]);
  const [fetching, setFetching] = useState(false);
  const [selectState, setSelectState] = useState(false);
  const originValRef = useRef([]);
  const handleChange = useHandler((ids, values) => {
    const result = values?.map((value, index) => {
      if (value.value) return value;
      const { tagDataId, value: v } = originValRef.current.find(
        (val) => val.tagDataId === ids[index],
      );
      return {
        value: tagDataId,
        label: v,
      };
    });
    if (result.length !== textValues.length) setSelectState(false);
    onChange(result);
  });

  useLaunch(() => {
    if (textValues.length === 0) {
      const options = value.map(({ value, label }) => ({
        tagDataId: value,
        value: label,
      }));
      originValRef.current = options;
      setTextValues(options);
      onChange(value);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [value]);

  const deboucedFetcher = useDebounce(
    (text) =>
      fetchLabelText({ value: text, tagId: id }).then((res) => {
        setFetching(false);
        setTextValues(camelizeKeys(res.data ?? []).slice(0, 20));
      }),
    300,
  );

  const handleSearchText = useHandler((text) => {
    setFetching(true);
    deboucedFetcher(text);
    setSelectState(false);
  });
  return (
    <div>
      <Select
        options={textValues.map(({ tagDataId, value }) => ({
          value: tagDataId,
          label: value,
        }))}
        mode="multiple"
        filterOption={false}
        onSearch={handleSearchText}
        style={{ minWidth: '100px' }}
        notFoundContent={fetching ? <Spin size="small" /> : null}
        value={(value ?? []).map(({ value }) => value)}
        onChange={handleChange}
        maxTagCount="responsive"
        dropdownRender={(allSelectValue) => (
          <div>
            <div style={{ padding: '4px 8px 8px 8px', cursor: 'pointer' }}>
              <Checkbox
                checked={selectState}
                onChange={(e) => {
                  if (e.target.checked === true) {
                    setSelectState(true);
                    onChange(
                      textValues
                        .map((item) => ({
                          value: item.tagDataId,
                          label: item.value,
                        }))
                        .concat(value || []),
                    );
                  } else {
                    setSelectState(false);
                    onChange([]);
                  }
                }}
              >
                全选
              </Checkbox>
            </div>
            <Divider style={{ margin: '0' }} />
            {/* Option 标签值 */}
            {allSelectValue}
          </div>
        )}
      />
      <Space>
        <ViewAll onChange={onChange} value={value} {...props} />
        <BatchUpload
          onChange={onChange}
          setSelectState={setSelectState}
          url="/api/dmp/tag/multiple_search"
          requestData={{
            tag_id: id,
          }}
          setTextValues={setTextValues}
        />
      </Space>
    </div>
  );
};

export default AdvancedAutoComplete;
